<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>test ajax1</title>
</head>
<body>
<h1>Ajax基本原理与XHR过程</h1>

<button id="btnGet" onclick="getData()">GET获取内容</button>
<div id="msg" ></div>
<br>
<input type="text" id="num_a" name="num_a">* <input type="text" id="num_b" name="num_b">=<input type="text" id="result" name="result">
<button id="btnCalc" onclick="do_ajax()" >ajax计算</button>
</body>
</html>
<script>
    function getData() {
        var xhr;
        //   xhr = new XMLHttpRequest();  // 直接新浏览器使用
       // 判断浏览器新旧不同实例化对象
        if(window.ActiveXObject){
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
        else if(window.XMLHttpRequest){
            xhr = new XMLHttpRequest();
        }
        else {
            throw new Error('当前浏览器不支持AJAX!');
        }

         // 请求初始化与发送
        xhr.open('GET','/content/');
        xhr.send();  //别写成sent();

        //指定xhr状态变化事件关联
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4 && xhr.status == 200 ){
                document.getElementById('msg').innerHTML = xhr.responseText;
            }
        }
    }

    function do_ajax(){
        var xhr = new XMLHttpRequest();
        var a = document.getElementById('num_a').value;
        var b = document.getElementById('num_b').value;

        xhr.onreadystatechange = function(){
            if(xhr.readyState==4 && xhr.status == 200){
                document.getElementById('result').value = xhr.responseText;
            }
        }

        xhr.open('GET','/ajax_calc/?a='+a+'&b='+b);
        xhr.send();
    }
</script>

